package com.company.base.interceptor;

import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.company.base.utils.CheckUtil;
import com.company.site.mode.wechatuser.OnlineUser;
import com.company.site.mode.wechatuser.WechatUser;
import com.company.site.user.UserService;

public class AuthInterceptor extends HandlerInterceptorAdapter {
	public static String OPERATOR = "onlineUser";
	@Resource
	UserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		OnlineUser onlineUser = (OnlineUser) session.getAttribute(OPERATOR);
		// 已经登录，放行
		//if(1==1){return true;}
		if(1==1){
			WechatUser wechatUserWechat=userService.getUserInfoByOpenid("oQSRbuHYciRcHXmFAEwRJmnKeVzY");
			//自动登录
			session.setMaxInactiveInterval(30*60); //登录有效时间为30分钟
			OnlineUser onlineUser2 = new OnlineUser();
			onlineUser2.setUserInfo(wechatUserWechat);
			session.setAttribute(AuthInterceptor.OPERATOR, onlineUser2);
			// session保存用户登陆信息userInfoSession
			session.setAttribute("userInfoSession", wechatUserWechat);
			return true;
			
		}
		if (onlineUser != null && onlineUser.getUserInfo() != null) {
			return true;
		}
		String resultUrl = request.getRequestURL().toString();
		// 放行：oauth获得openid，wechat菜单回复，注册验证码，注册大队ajax联动显示
		if (resultUrl.contains("oauth") 
				|| resultUrl.contains("wechat")
				|| resultUrl.contains("getOrgIdAndName")
				|| "post".equalsIgnoreCase(request.getMethod())
				|| resultUrl.contains("fixNum")
				|| resultUrl.contains("cheat")
				|| resultUrl.contains("main")
				|| resultUrl.contains("result")
				|| resultUrl.contains("sub")
				|| resultUrl.contains("login"))
				 {
			return true;
		}
		// onlineUser没有，请求微信oauth获得openid
		if (CheckUtil.isEmpty(onlineUser)
				|| CheckUtil.isEmpty(onlineUser.getUserInfo())) {
			String param = request.getQueryString();
			if (param != null) {
				resultUrl += "?" + param;
			}
			try {
				resultUrl = java.net.URLEncoder.encode(resultUrl, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			// 请求的路径
			String contextPath = request.getContextPath();
			System.out.println("preHandle:跳转到获取code的方法：" + contextPath
					+ "/oauth/getCode.htm?resultUrl=" + resultUrl);
			response.sendRedirect(contextPath + "/oauth/getCode.htm?resultUrl="
					+ resultUrl);
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	

}
